﻿using System;
using System.Web;
using System.Net;
using System.IO;

namespace _18miljard
{
	public class WebReader
	{
		public static string ReadUrl(string url)
		{
			HttpWebResponse response = null;
			Stream receiveStream = null;
			StreamReader readStream = null;
			string htmlResponse = null;

			try
			{
				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

				// Set some reasonable limits on resources used by this request
				request.MaximumAutomaticRedirections = 4;
				request.MaximumResponseHeadersLength = 4;
				// Set credentials to use for this request.
				request.Credentials = CredentialCache.DefaultCredentials;

				response = (HttpWebResponse)request.GetResponse();

				// Get the stream associated with the response.
				receiveStream = response.GetResponseStream();

				// Pipes the stream to a higher level stream reader with the required encoding format. 
				readStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8);

				htmlResponse = readStream.ReadToEnd();

				return htmlResponse;
			}
			catch (Exception e)
			{
				throw new Exception("Error reading url", e);
			}
			finally
			{
				if (readStream != null)
					readStream.Close();

				if (response != null)
					response.Close();
			}
		}
	}
}